// const mqttSettings = require("./settings/mqtt_settings.json"); //MQTT配置参数
// const mqttHost = mqttSettings.mqttHost; //MQTT host
// const mqttPort = mqttSettings.mqttPort; //MQTT Port
// const mqttUsername = mqttSettings.mqttUsername;
// const mqttPassword = mqttSettings.mqttPassword;
// const mqttBaseId = mqttSettings.baseId;
// const mqttServerId = mqttSettings.serverId;

var mqtt = require("mqtt");
var msgpack = require("msgpack-lite");
const mysql = require("mysql");

var moment = require("moment");
moment.locale("zh-cn");

// 建立mqtt链接
var client = mqtt.connect({
  host: "mqtt.bconimg.com",
  port: 1883,
  username: "",
  password: ""
});

startAnimal();

function startAnimal() {
  const connection = mysql.createConnection({
    host: "localhost",
    port: "3306",
    user: "root",
    password: "yjjind",
    database: "TestDataBase"
  });
  connection.connect();

  client.on("connect", function () {
    // b5e1726951d82efb3ab70a18e0de4d6b9a760aaed0c70a57895a758aa50279cf/animalTag
    console.log("------- start -------");
    client.subscribe("AnimalTag");
  });

  // JSON.stringify(sendData)

  client.on("message", function (topic, message) {
    if (message.toString() !== "") {
      var data = msgpack.decode(message);
      // console.log(data);
      let v = data.v;
      let mid = data.mid + "";
      let time = data.time + "";
      let ip = data.ip;
      let mac = data.mac;
      // client.end();
      // console.log("======>main mac: ", mac);

      data.devices.forEach(item => {
        let itemData = JSON.parse(JSON.stringify(item));

        if (
          itemData.data[8] === 0x02 &&
          itemData.data[9] === 0x01 &&
          itemData.data[10] === 0x06 &&
          itemData.data[11] === 16
        ) {
          // console.log(itemData);
          let bufferData = Buffer.from(itemData.data, "hex");
          // console.log(bufferData);
          let tagMac = bufferData.slice(1, 7).toString("hex").toUpperCase();
          let stepNum = bufferData.slice(12, 16).toString("ascii"); // 记步数
          let battery = itemData.data[16].toString(); // 电池电量
          let targetTem = bufferData.slice(17, 21).toString("ascii"); // 目标温度
          let environmentTem = bufferData.slice(21, 25).toString("ascii"); // 环境温度
          let dateTime = moment().format("YYYY-MM-DD HH:mm:ss");

          // parseInt(moment(new Date(updt)).format('YYYY'))

          // console.log("======>dateTime: ", dateTime);

          // console.log(stepNum, battery, targetTem, environmentTem);

          // let sqlStr = `insert into animal_history (mac, tagMac, mid, time, ip, v, stepNum, battery,
          //  targetTem, environmentTem, dateTime)
          // values ("${mac}", "${tagMac}", "${mid}", "${time}", "${ip}", "${v}", "${stepNum}", "${battery}",
          //  "${targetTem}", "${environmentTem}", "${dateTime}")`;

          // connection.query(sqlStr, function(error, results) {
          //   console.log("--------");
          //   if (error) {
          //     console.log(
          //       "插入记录失败error: ",
          //       error,
          //       "插入记录失败results: ",
          //       results
          //     );
          //   } else {
          //     console.log("插入记录成功: ", results);
          //     // callback();
          //   }
          // });
        }
      });
      client.publish("b5e1726951d82efb3ab70a18e0de4d6b9a760aaed0c70a57895a758aa50279cf/animalTag", JSON.stringify({
        title: "hello"
      }));
      // console.log(deviceData);
    }
  });

  // client.subscribe();
}